package com.ly.common.base.service.impl;


import com.ly.common.base.page.PageList;
import com.ly.common.base.query.BaseQuery;
import com.ly.common.base.repository.BaseRepository;
import com.ly.common.base.service.IBaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;

import java.util.List;

/**
 * 通过业务接口实现类
 * @Auther: lzw
 * @Date: 2018/6/4
 */
public abstract class BaseServiceImpl<T> implements IBaseService<T> {

    @Autowired
    protected BaseRepository<T,Integer> baseRepository;

    @Override
    public T findOne(Integer id) {
        return (T)baseRepository.findOne(id);
    }

    @Override
    public void delete(Integer id) {
        baseRepository.delete(id);
    }

    @Override
    public long count() {
        return baseRepository.count();
    }

    @Override
    public PageList<T> findPage(BaseQuery baseQuery) {
        //第一个参数是页码(从0 开始) 但一般页面展示是从1开始 所以这里减一
        PageRequest pageRequest=new PageRequest(baseQuery.getPageIndexOffset(),baseQuery.getPageSize());
        //返回参数包含了 记录总数 总页数 当前页码 等信息
        Page<T> page=baseRepository.findAll(baseQuery.toSpecification(),pageRequest);
        //获得数据集
        List<T> dictParentDomainList=page.getContent();
        // 初始化pageList
        PageList<T> pageList = new PageList<>(dictParentDomainList, baseQuery.getPageIndex(),
                baseQuery.getPageSize(),page.getTotalPages(), page.getTotalElements());
        return pageList;
    }

    @Override
    public List<T> findAll() {
        return baseRepository.findAll();
    }
}
